var userWebGesture = new function () {
    var me = this;
    var url = document.location.href;
    me.LoadAttempts = 0;
    me.el0 = null;
    me.el = null;
    me.els = [];

    me.Load = function () {
        me.Log("page url", url);

        if (window.$ == null) {
            me.LoadAttempts++;
            me.Log("$ is null ", me.LoadAttempts);

            if (me.LoadAttempts < 5) {
                window.setTimeout(function () {
                    me.Load();
                }, 1000);
            }
            else {
                alert("$ is null - try again");
            }

            return;
        }

        if (url.match(/getpocket\.com/ig) !== null) { // share from pocket to gmail
            me.Log("share from pocket to gmail", url);

            var url1 = $(".original a").prop("href");
            var body = url1.substring(url1.indexOf("url=") + 4);
            var title = $(".reader_head h1").text();
            var targ = "https://mail.google.com/mail/?view=cm&fs=1&tf=1&source=mailto&su=" + title + "+%5Bpocket%5D&body=" + body;
            window.open(targ, null, "width=800,height=350,left=0,top=0;");
        }
        else if (url.match(/feedly\.com/ig) !== null) { // send to pocket from feedly
            me.Log("send to pocket from feedly", url);
            var url1 = $(".inlineFrame .entryTitle").prop("href");
            var title = $(".inlineFrame .entryTitle").text();
            var targ = "https://getpocket.com/edit?url=" + encodeURIComponent(url1) + "&title=" + title + "&doclose=1";
            var f = $("#user-web-gesture-iframe");
            window.open(targ, null, "width=700,height=350,left=0,top=0;");
        }
        else { // send to pocket from anywhere
            me.Log("new readr", url);
            $('body').bind("mousemove.uwg", me.MouseMove);
        }
    };

    me.MouseMove = function (e) {
        me.Log("mousemove");

        $('body').unbind("mousemove.uwg");

        me.el0 = $(e.target);
        me.el0.css("background-color", "orange");
        me.el = me.el0;
        me.els.push(me.el);

        var main = me.FindMain(me.el);

        if (main) {
            me.PsOnly = true;
            me.el = main;
            me.Found();
        }
        else {
            me.PsOnly = false;
            me.Log("not found main", "adding bindings");

            $('body').bind("keyup.uwg", me.KeyUp);
            $('body').bind("mouseup.uwg", me.MouseUp);

            document.oncontextmenu = function () { return false; };
        }
    };

    me.FindMain = function (el) {
        var ps = el.find("p");

        //me.Log("ps.length", ps.length);

        if (ps.length > 3) {
            try {
                me.Log("found main", el.prop("tagName") + " id='" + el.attr("id") + "' class='" + el.prop("class") + "'");
                //console.log(el);
            }
            catch (ex) {
                me.Log("found main", "failed to log el " + ex.message);
            }
            return el;
        }

        if (el.parent().length == 0) {
            return null;
        }

        return me.FindMain(el.parent());
    };

    me.KeyUp = function (e) {
        me.Log("keyup " + e.keyCode);
        switch (e.keyCode) {
            case 27: //esc
                me.CancelFind();
                break;
            case 13: //enter
                me.Found();
                break;
            case 37: //back
                if (me.el != me.el0) {
                    me.el.css("background-color", "white");
                    me.els.pop();
                    me.el = me.els[me.els.length - 1];
                }
                break;
            case 39: //forward
                me.FindNext();
                break;
        }
    };

    me.MouseUp = function () {
        me.Log("mouseup " + event.button, this);

        switch (event.button) {
            case 0:
                me.FindNext(); //chrome
                break;
            case 1:
                if (document.all) { //IE
                    me.FindNext();
                }
                break;
            case 2: //right click
                window.setTimeout(function () {
                    me.Found();
                }, 1);
                break;
        }
    };

    me.FindNext = function () {
        if (me.el[0].tagName == "BODY") {
            return;
        }

        me.el = me.el.parent();

        if (me.el[0].tagName == "BODY") {
            me.el.css("background-color", "red");
        }
        else {
            me.el.css("background-color", "gold");
        }

        me.el.addClass("uwg-el");
        me.els.push(me.el);

    };

    me.Exclude = /share|sharing|social|twitter|tool|related|comment|discussion|extra|contentWellBottom|kudo|$ad|keywords|secondary-column|furniture|hidden|embedded-hyper/;

    me.Found = function () {
        me.Log("found")

        var popout = false;
        var title = document.title;
        var root = ($("#user-web-gesture-js").data("local") == 1) ?
            'https://localhost:44300/' :
            "https://user-web.googlecode.com/svn/trunk/";

        me.CancelFind();

        me.OriginalHtml = $("html").html();

        /* ":hidden" matches <nyt_text class="uwg-el" style="background-color: white;">
        *  I guess because it's custom tag
        */
        if (popout) {
            var rem = me.el.find("iframe, script, link, button, input, form").remove();

            me.Log("rem---------------...");

            rem.each(function () {
                me.Log($(this).html());
            });

            var hid = me.el.find("*").filter(function (a, b, c) {
                return this.className.match(me.Exclude) !== null ||
                typeof (this.id) != "string" ||
                this.id.match(me.Exclude) ||
                $(this).css('visibility') == 'hidden';
            });

            me.Log("hid---------------...");

            hid.each(function () {
                me.Log($(this).html());
            });

            hid.remove();

            me.el.find('*').attr('style', '');

            me.FindMainContainers(me.el);

            var containerClass = me.el.hasClass("readr-container") ? " readr-container" : "";

            html = me.el.html();

            var w = window;

            var test = false;

            if (test) {
                w = window.open();
                w.document.write("<html>");
            }
            else {
                $("head").remove();
                $("body").remove();
            }

            w.document.write("<head>");
            w.document.write("<title>" + title + "</title>");
            w.document.write("<link rel='stylesheet' type='text/css' href='" + root + "Styles/readr.css?" + new Date().valueOf() + "'>");
            w.document.write("</head>");
            w.document.write("<body>");
            w.document.write("<div class='readr-inner" + containerClass + "'>");
            w.document.write("<h1>" + title + "</h1>");
            w.document.write(html);

            w.document.write("<div class='readr-links'>");

            var u = document.location.href.split("#")[0].split("/");

            while (u.length > 2) {
                w.document.write("<a href=" + u.join("/") + ">" + u.join("/") + "</a><br />");
                u.pop();
            }

            w.document.write("</div>");
            w.document.write("</div>");
            w.document.write("</body>");

            if (test) {
                w.document.write("</html>");
            }

            me.el = null;
            me.el0 = null;
            me.els = [];
        }
        else {
            if (me.PsOnly) {
                me.FindMainContainers(me.el);
            }
            else {
                me.el.addClass("readr-container"); ;
            }

            //.attr('style', function (i, s) { return s + 'width: 100px !important;' });
            var match = me.PsOnly ? ".readr-containerx, .readr-container p, .readr-container ul" : ".readr-containerx, .readr-container *";

            $(match)
                .attr('style',
                    "font-family: Corbel, URW Gothic L, Ubuntu Light, DejaVu Sans, Courier New, Arial !important;" +
                    "font-size: 16px !important;" + /* reading-font-size */
                    "line-height: 22px !important;" + /* reading-line-height */
                    "text-align: justify !important;" +
                    "background-color: #ffffff !important;" +
                    "background-image: none !important;" +
                    "color: #444 !important;"
                );

            $(".readr-container a")
                .attr('style',
                    "font-family: Corbel, URW Gothic L, Ubuntu Light, DejaVu Sans, Courier New, Arial !important;" +
                    "font-size: 16px !important;" + /* reading-font-size */
                    "line-height: 22px !important;" + /* reading-line-height */
                    "text-decoration: none !important;" +
                    "color: #444 !important;" +
                    "border-bottom: 1px dotted #ddd !important;"
                );

            $(".readr-container")
                .attr('style',
                    "background-color: #ffffff !important;"
                );
        }
    };

    me.CancelFind = function () {
        $("*").unbind(".uwg");
        $(".uwg-el").css("background-color", "white");
        me.el0.css("background-color", "white");
        document.oncontextmenu = null;
    };

    me.FindMainContainers = function (content) {
        var paras = $(content).find("p");
        var parents = [];

        paras.parent().data("readrParentId", null)

        //me.Log("paras.length", paras.length);

        var parentId = 0;

        for (var i = 0; i < paras.length; i++) {
            var $para = $(paras[i]);
            var $parent = $para.parent();

            if ($parent.data("readrParentId") == null) {
                $parent.data("readrParentId", parentId);
                parents[$parent.data("readrParentId")] = { el: $parent, count: 1, parentId: parentId };
                parentId++;
            }
            else {
                var id = $parent.data("readrParentId");

                parents[id].count++;
            }
        }

        if (parentId > 0) {
            for (var j in parents) {
                if (parents[j].count > 0) {
                    parents[j].el.addClass("readr-container"); ;
                }

                //userWeb.Log("parent[" + i + "]", parents[i].count);
            }
        }
    };

    me.Log = function (text1, text2) {
        if (text2 != null) {
            if (text1.length < 20) {
                text1 = text1 + Array(21 - text1.length).join(" ");
            }

            console.log("[user-web-gesture]     " + text1 + ": " + text2);
        }
        else {
            console.log("[user-web-gesture]     " + text1);
        }
    };
};

userWebGesture.Load();